#!/bin/bash

# HomeBox Single Binary Build Script
# This script builds HomeBox as a single executable with embedded frontend

set -e

echo "🏠 Building HomeBox Single Binary..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Build frontend first
echo -e "${YELLOW}📦 Building frontend...${NC}"
cd frontend

# Install dependencies and build
pnpm install
pnpm run build

# Check if build was successful
if [ ! -d ".output/public" ]; then
    echo -e "${RED}❌ Frontend build failed - .output/public directory not found${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Frontend built successfully${NC}"

# Copy frontend assets to backend
echo -e "${YELLOW}📁 Copying frontend assets to backend...${NC}"
cd ..
rm -rf backend/app/api/static/public
mkdir -p backend/app/api/static/public
cp -r frontend/.output/public/* backend/app/api/static/public/

# Generate API docs
echo -e "${YELLOW}📚 Generating API documentation...${NC}"
cd backend

# Install swag if not exists
if ! command -v swag &> /dev/null; then
    echo -e "${YELLOW}Installing swag...${NC}"
    go install github.com/swaggo/swag/cmd/swag@latest
fi

# Generate swagger docs
swag fmt --dir=./app/api
swag init --dir=./app/api,./internal/core/services,./internal/data/repo --parseDependency --output ./app/api/static/docs

# Build single binary
echo -e "${YELLOW}🔨 Building single binary...${NC}"

# Build for current platform
go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ../homebox-single ./app/api

# Build for multiple platforms (optional)
if [ "$1" = "all" ]; then
    echo -e "${YELLOW}🔨 Building for all platforms...${NC}"
    
    # Windows AMD64
    GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ../homebox-windows-amd64.exe ./app/api
    
    # Linux AMD64
    GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ../homebox-linux-amd64 ./app/api
    
    # macOS AMD64
    GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ../homebox-darwin-amd64 ./app/api
    
    # macOS ARM64
    GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ../homebox-darwin-arm64 ./app/api
    
    echo -e "${GREEN}✅ Multi-platform builds completed${NC}"
fi

echo -e "${GREEN}✅ Single binary build completed!${NC}"
echo -e "${GREEN}📦 Binary location: $(pwd)/../homebox-single${NC}"

# Make it executable on Unix systems
chmod +x ../homebox-single

echo -e "${GREEN}🚀 Ready to run! Use: ./homebox-single${NC}"